﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Channels;
using System.ServiceModel;
using System.Diagnostics;

namespace NntpTransport
{
	public class NntpRequestChannel : NntpChannelBase, IRequestChannel
	{
		readonly Uri via;
		readonly object writeLock;

		public NntpRequestChannel(BufferManager bufferManager,
			MessageEncoderFactory encoderFactory,
			EndpointAddress address,
			NntpRequestChannelFactory parent,
			Uri via)
			: base(bufferManager, encoderFactory, address, parent, parent.Streamed, parent.MaxReceivedMessageSize)
		{
			this.via = via;
			this.writeLock = new object();
		}

		public IAsyncResult BeginRequest(Message message, TimeSpan timeout, AsyncCallback callback, object state)
		{
			throw new Exception("The method or operation is not implemented.");
		}

		public IAsyncResult BeginRequest(Message message, AsyncCallback callback, object state)
		{
			return BeginRequest(message, DefaultReceiveTimeout, callback, state);
		}

		public Message EndRequest(IAsyncResult result)
		{
			throw new Exception("The method or operation is not implemented.");
		}

		public Message Request(Message message, TimeSpan timeout)
		{
			ThrowIfDisposedOrNotOpen();
			lock(this.writeLock)
			{
				try
				{
					Trace.WriteLine("NntpRequestChannel.Request>");
					//File.Delete(PathToFile(Via, "reply"));
					//using (FileSystemWatcher watcher = new FileSystemWatcher(Via.AbsolutePath, "reply"))
					//{
					//   ManualResetEvent replyCreated = new ManualResetEvent(false);
					//   watcher.Changed += new FileSystemEventHandler(
					//      delegate(object sender, FileSystemEventArgs e) { replyCreated.Set(); }
					//   );
					//   watcher.EnableRaisingEvents = true;
					//   WriteMessage(PathToFile(via, "request"), message);
					//   if (!replyCreated.WaitOne(timeout, false))
					//   {
					//      throw new TimeoutException(timeout.ToString());
					//   }
					//}
				}
				catch(Exception exception)
				{
					throw exception;
				}
				
				return null;// ReadMessage(PathToFile(Via, "reply"));
			}
		}

		public Message Request(Message message)
		{
			return Request(message, DefaultReceiveTimeout);
		}

		public Uri Via
		{
			get { return this.via; }
		}

	}
}
